//
//  CZUserAccountViewModel.swift
//  WHWeiBo
//
//  Created by Li Changjian on 16/7/12.
//  Copyright © 2016年 Li Changjian. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {
/// 单例
    static let sharedUserAccount: CZUserAccountViewModel = CZUserAccountViewModel()
/// 用户对象,由沙盒中解档
    var userAccount: CZUserAccount? {
        return CZUserAccount.loadUserAccount()
    }
    
    private override init() {
        super.init()
    }
    
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        
        let result = userAccount?.expires_date?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            return token
        }else {
            return nil
        }
        
    }
    
    var isLogin: Bool {
        return accessToken != nil
    }
    
    

    func requestAccessToken(code: String, callBack: (isSuccess: Bool) -> ()) {
        
        CZNetWorkingTool.sharedNetWorkTool.requestAccessToken(code) { (response, error) -> () in
            //请求失败
            if error != nil {
                print(error)
                callBack(isSuccess: false)
                return
            }
            //请求成功
            guard let dict = response as? [String: AnyObject] else {
                callBack(isSuccess: false)
                return
            }
            let user = CZUserAccount(dict: dict)
//            print(user)
            
            //根据由code获取到的accessToken获取用户信息
            self.requestUserAccount(user, callBack: callBack)
            
        }
    }
    
    //根据accessToken获取用户信息
    func requestUserAccount(userAccount: CZUserAccount, callBack: (isSuccess: Bool) ->()) {
        
        CZNetWorkingTool.sharedNetWorkTool.requestUserAccount(userAccount) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isSuccess: false)
                return
            }
            //成功回调
            //            print(response)
            guard let dict = response as? [String : AnyObject] else {
                callBack(isSuccess: false)
                return
            }
            //返回字典
            userAccount.name = dict["name"] as! String!
            userAccount.avatar_large = dict["avatar_large"] as! String!
            
            //            print(userAccount)
            if userAccount.saveUserAccount() {
                print("保存账号信息成功")
                callBack(isSuccess: true)
            }else{
                callBack(isSuccess: false)
            }
            
            
            
        }
    }

    
}
